import os,sys,requests,re,json,time
import picmap
import reverse_geocoder as rg
import numpy as np 
"""
获取图片信息  
p:{zoom:放大级别3～19级,bounds:{ne:{lat:x,lng:y},sw:{}}巨型范围左上角和右下角的点
"""
def getPoints(p):
        print(p)
        where="x>%s and x<%s and y>%s and y<%s" % tuple(p['range'].split(','))
        for name in ('name','time','path'):
            if name=='path' and p.get(name): 
                name="pid"
                p['pid']=picmap.db.queryId('path',"path='%s'" % p['path'])
            if p.get(name) : 
                where+=" and `%s` like '%s'" % (name,p[name]+"%")
        all=picmap.db.queryObject('pic',where)

        n=max(2,int(p['zoom'])-8); points={}; tree={'name':{},'time':{},'path':{},'current':{'name':'','time':''}}
        n=int((int(p['zoom'])-3)/2)+1;   #3~19一共16级转换为1～8级别
        #40076000m    360度
        #111322             1
        #1                          0.00001    5尾小数足够  
        for v in all:
            # for k in ['x','y']:
            (x0,y0)=[float(v['x']),float(v['y'])]
            x=str(v['x'])[:n].strip('.')
            y=str(v['y'])[:n+1].strip('.')
            if n<=3:
                x=str(int(v['x'])); y=str(int(v['y']))
                if n<3: 
                    n=10**(3-n)
                    if x<0 :x=180+(180+x)
                    if y<0 :y=90+(90+y)
                    x=int(x/360*1000)
                    y=int(y/180*1000)
                    x="0<3d".format(int(x/n))
                    y="0<3d".format(int(y/n))
                    
            #补充长度到n
            key=','.join([x,y])
            if not points.get(key): 
                points[key]={'x':x,'y':y,'count':[[x0],[y0]],'name':'','id':key}
            else:
                points[key]['count'][0]+=[x0]
                points[key]['count'][1]+=[y0]

            for k in ['name','time']:
                p=tree[k]
                for kk in v[k].split(" "):
                    if p.get(kk) :
                        p=p[kk] 
                    else :
                        p[kk]={}
                        p=p[kk]
            if not v['pid'] == None :            
                tree['path'][v['pid']]=  1 

        for k in ['name','time']:
            p=tree[k]
            while len(p) ==1: 
                kk=tuple(p.keys())[0]
                p=p[kk]
                tree['current'][k] += kk+" "  
            tree[k+'List']=list(p.keys())
        # print(tree)
        ids=','.join([str(i) for i in tree['path'].keys()])
        tree['pathList']=[v[0] for v in picmap.db.query('path','id in (%s)' % ids,select='path')]
        for k in points:
            v=points[k]
            v['x']=np.mean(v['count'][0])
            v['y']=np.mean(v['count'][1])
#            v['x']=v['count'][0][0] 
#            v['y']=v['count'][1][0] 
            v['count']=len(v['count'][0])
        return {'points':tuple(points.values()),'options':{'name':tree['nameList'],'time':tree['timeList'],"path":tree['pathList']},'current':tree['current']}

        # return  [ { "count": 1669, "name": "宝安", 'x': 113.89006042480469, 'y': 22.56084442138672, },  
        #     { 'count': 2606, 'id':11,'name': "福田", 'x': 114.06153106689453, 'y': 22.527225494384766,'vg':"114.111476,22.53826;114.11101,22.553809;114.110718,22.572663;114.104188,22.571248;114.09912,22.570126;114.097927,22.570907;114.096157,22.57382;114.092451,22.575672;114.088531,22.575548;114.086225,22.574988;114.082806,22.580751;114.082324,22.583101;114.080293,22.585229;114.074145,22.590958;114.070218,22.59237;114.064793,22.592853;114.062517,22.59162;114.061184,22.590877;114.060502,22.590254;114.060232,22.589301;114.06008,22.588173;114.059228,22.587632;114.058366,22.587959;114.057604,22.588363;114.055736,22.588149;114.054432,22.588279;114.053419,22.588753;114.052645,22.589547;114.048979,22.589615;114.047511,22.589768;114.043953,22.588989;114.042626,22.589326;114.042053,22.589337;114.039096,22.588282;114.037909,22.587766;114.035805,22.587737;114.033765,22.58794;114.032558,22.588289;114.031583,22.588167;114.029275,22.586823;114.028562,22.586321;114.025686,22.585283;114.023356,22.585214;114.022813,22.585474;114.020037,22.585583;114.014297,22.583828;114.013062,22.582543;114.011882,22.581938;114.011372,22.578076;114.011446,22.576973;114.011664,22.575449;114.011721,22.57455;114.011346,22.573541;114.010378,22.572445;114.009725,22.57081;114.009912,22.568585;114.010109,22.567706;114.010248,22.56665;114.010941,22.565995;114.011322,22.565225;114.011643,22.564569;114.01173,22.563839;114.011809,22.562513;114.010317,22.562116;114.008778,22.561978;114.007665,22.56197;114.005656,22.561548;114.003866,22.561101;114.004507,22.56024;114.004585,22.558977;114.004513,22.557799;114.004826,22.556744;114.005391,22.556209;114.006165,22.555908;114.005901,22.555148;114.004546,22.554969;114.003896,22.554681;114.002525,22.552873;114.003285,22.551603;114.00332,22.550567;114.002976,22.549448;114.003063,22.54727;114.003004,22.545363;114.003217,22.543581;114.003604,22.541511;114.003863,22.540152;114.004089,22.538911;114.00331,22.538728;114.001703,22.539097;114.001542,22.538457;114.002152,22.537501;114.001614,22.536624;114.000722,22.536727;114.000297,22.536231;113.999936,22.535205;113.999847,22.533294;114.00258,22.524318;114.006427,22.511619;114.021191,22.507073;114.031597,22.506086;114.048162,22.509099;114.064504,22.50594;114.067075,22.509363;114.068667,22.514205;114.075949,22.520487;114.080682,22.521372;114.08719,22.519015;114.094594,22.525418;114.089216,22.532223;114.094151,22.535578;114.107081,22.538324" }, 
        #      { 'count': 2221, 'name': "罗湖", 'x': 114.13809967041016, 'y': 22.554670333862305, }
        # ];
        
#获取当前坐标和级别 
def getPostion():
        #z: 3~19级 
        rt=picmap.db.queryObject('pic','1=1 order by id desc','x,y',1)
        if len(rt)==0:
            rt={"x":114.06153106689453,"y":22.527225494384766}
        else:
            rt=rt[0]

        rt['z']=15
        return rt
    
def  openId(p):
        ##图片展示需要调用界面  
        [x,y]=p['id'].split(',')
        all=picmap.db.queryObject('pic left join path on path.id=pic.pid',"x like '%s' and y like '%s'" %(x+"%",y+"%") ,'path||file as file,time')
        if picmap.ppid :
            picmap.gui_do('openPicWindow',p['id'])
        return all

def openConfig():
        ##操作界面激活显示  
        picmap.gui_do('openConfig')
        pass

def openMain():
    ##操作界面激活显示  
    picmap.gui_do('openMain')
    pass

def get_city_info(result):
        #https://blog.csdn.net/haiziccc/article/details/103959965
        Lat, Lon = result
        loc = rg.search(result)
        city=loc[0]['name']#城市
        county=loc[0]['admin2']#郡
        state=loc[0]['admin1']#州
        country=loc[0]['cc']#国家
        return " ".join([country,state,county,city])
        print(loc)
#        url = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format('E4805d16520de693a3fe707cdc962045', Lat, Lon)
        url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=UXNfXeDbwzkcGkSugykBYF8kiuweOAAY"+"&output=json&coordtype=wgs84ll&location=" + str(Lat) + ',' + str(Lon)
        response = requests.get(url).json()
        status = response['status']
        if status == 0:
            address = response['result']['formatted_address']
            return address
        else:
            print('baidu_map error ')
            print(response)
            return ""
            
def application(env,Response):    
    ctype="text/plain"
    tmap={
        ".js":'application/x-javascript',
        ".html":'text/html',
        '.css': 'text/css',
        '.json': 'application/json',
         '.xml': 'text/xml',
         '.wsdl': 'text/xml',
         '.svg': 'text/xml',
          '.jfif': 'image/jpeg',
        '.jpe': 'application/x-jpe',
        '.jpeg': 'image/jpeg',
        '.jpg': 'application/x-jpg',
        '.png': 'application/x-png',
    }
    if env['uri'].startswith("/api/"):
        func=os.path.basename(env['file'])
        print("call "+func)
        responseBody= globals()[func](env['params']) if env['params'] else globals()[func]()
        if type(responseBody) != "str": 
            responseBody=json.dumps(responseBody)
            ctype=tmap['.json']
        # print(responseBody)
    else:
        filePath=env['file']
        file =open(filePath,'r',encoding='utf8')
        responseBody = file.read()
        ext=re.sub(r'.+(\.\w+)$',r'\1',filePath)
        if tmap.get(ext):
            ctype=tmap[ext] 
        
    status = 'HTTP/1.1 200 OK'
    responseHeaders = [('Server','kpyhs'),('Date','%s'%time.ctime()),('Content-Type',"%s; charset=utf-8" % ctype),('Access-Control-Allow-Origin','*')]
    Response(status,responseHeaders,responseBody)
    return True
